package com.wenjunwu.blog.common;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.wenjunwu.blog.dao.SystemRoleDao;
import com.wenjunwu.blog.dao.SystemUserDao;
import com.wenjunwu.blog.entity.SystemRole;
import com.wenjunwu.blog.entity.SystemUser;

@Component
public class CustUserDetailsService implements UserDetailsService {
	static final Logger logger = LoggerFactory.getLogger(CustUserDetailsService.class);

	@Autowired
	private SystemUserDao systemUserDao;

	@Autowired
	private SystemRoleDao systemRoleDao;

	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		SystemUser systemUser = systemUserDao.findUser(username);
		logger.info("SystemUser : {}", systemUser);
		if (systemUser == null) {
			logger.info("SystemUser not found");
			throw new UsernameNotFoundException("用户不存在");
		}
		return new User(systemUser.getUsername(), systemUser.getPassword(), true, true, true, true,
				getGrantedAuthorities(systemUser));
	}

	private List<GrantedAuthority> getGrantedAuthorities(SystemUser systemUser) {
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		List<SystemRole> listSystemRole = systemRoleDao.selectByUsername(systemUser.getUsername());
		for (SystemRole systemRole : listSystemRole) {
			logger.info("SystemRole : {}", systemRole);
			authorities.add(new SimpleGrantedAuthority("ROLE_" + systemRole.getRoleName()));
		}
		logger.info("authorities : {}", authorities);
		return authorities;
	}
}
